package aynu.hd.Config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器的使用
@Configuration
public class LoginConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                Object account = request.getSession().getAttribute("user");
                if (account == null) {
                    //跳转到登录页面
                    response.sendRedirect("/login");
                    return false;
                }
                return true;
            }
        })
                .addPathPatterns("/**")
                .excludePathPatterns("/", "/login", "/userLogin", "/userBack", "/registerUser", "/verification", "/useRegister", "/forget", "/verificationForget", "/userLoginForget",
                        "/js/**", "/css/**", "/fonts/**", "/img/**", "/assets/**");
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
    }
}
